<script setup lang="ts">
import { loginAPI } from '@/apis/user';
import { FORMDATA_KEY } from '@/components';
import { useUserStore } from '@/stores/user';
import type { LoginParams } from '@/types/user';
import type { AxiosError } from 'axios';
import { ElMessage } from 'element-plus'; // 正确导入 ElMessage
import type { FormInstance, FormRules } from 'element-plus';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

// 获取 store
const store = useUserStore()

// 表单数据
const formData = ref<LoginParams>({
  mobile: '19124642735',
  code: '246810'
})
// 记住我
const remember = ref(false)

// 表单校验规则
const formRules = ref<FormRules<LoginParams>>({
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    // { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    //  len 设置验证规则的长度
    { len: 6, message: '验证码不正确', trigger: 'blur' }
  ]
})

// 本地取出数据赋值
onMounted(() => {
  //
  const jsonStr = localStorage.getItem(FORMDATA_KEY)
  //
  if (jsonStr !== null) {
    try {

      const userPassObj = JSON.parse(jsonStr)

      if (userPassObj && typeof userPassObj.remember === 'boolean') {

        remember.value = userPassObj.remember
      }
    } catch (error) {

      console.error('Failed to parse local storage data:', error)
    }
  }
})

// 表单实例，用于整个表单校验
const loginFormRef = ref<FormInstance>()

// 获取路由实例 用于页面跳转 注意书写位置 只能是 setup 顶级 不能写到事件处理函数内部
const router = useRouter()
// 提交表单-登录
const submitForm = () => {
  // 表单整体校验
  loginFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 发送请求
        const res = await loginAPI(formData.value)
        // console.log('res', res)

        // 检查用户是否选择了记住登录状态
        if (remember.value) {
          localStorage.setItem(FORMDATA_KEY, JSON.stringify({
            remember: remember.value,
            mobile: formData.value.mobile,
            code: formData.value.code
          }))
        } else {
          // 如果用户没有选择记住登录状态，从本地存储中移除之前保存的表单数据
          localStorage.removeItem(FORMDATA_KEY)
          // 停止往后继续执行代码
          return
        }

        // 调用 store 的方法保存 token
        // console.log('token', res.data.token)
        store.setToken(res.data.token)
        // 获取之前存储的目标页面路径
        const redirectPath = localStorage.getItem('redirectpath') || '/'
        // 重定向到目标页面
        router.push(redirectPath)
        // 清除存储的目标页面路径
        localStorage.removeItem('redirectPath')
        // 用户提示
        ElMessage.success('登录成功')
      } catch (e) {
        const errors = e as AxiosError<{ message: string }>;
        // 如果发生错误，显示错误信息
        ElMessage.error(errors.response?.data.message || '登录失败')
        // console.dir(e)
      }
    }
  })
}
</script>

<template>
  <div class="container">
    <el-card>
      <!-- 图片 -->
      <img class="logo" src="@/assets/images/logo.png" alt="">
      <!-- 图标 -->
      <el-form ref="loginFormRef" :model="formData" :rules="formRules">
        <el-form-item prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item prop="code">
          <el-input v-model="formData.code" placeholder="请输入验证码"></el-input>
        </el-form-item>

        <el-form-item prop="remember">
          <el-checkbox v-model="remember">我已阅读并同意「用户协议」和「隐私条款」</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button @click="submitForm()" type="primary">登 录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="less">
.container {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: url(@/assets/images/login.png);

  .el-card {
    width: 440px;
    height: 380px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.1);

    .logo {
      width: 200px;
      display: block;
      margin: 0 auto 20px;
    }

    .el-form {
      padding: 0 20px;

      .el-button {
        width: 100%;
      }
    }
  }
}
</style>
